package com.intersult.nutils.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

/**
 * @author Dieter Kaeppel
 * @date   16.11.2011
 */
public class Streamer implements Runnable {
	private InputStream inputStream;
	private OutputStream outputStream;
	private int size = 8192;
	
	public Streamer(InputStream inputStream, OutputStream outputStream) {
		this.inputStream = inputStream;
		this.outputStream = outputStream;
	}

	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
	
	@Override
	public void run() {
		init();
		try {
			byte[] buffer = new byte[size];
			for (;;) {
				int length = read(inputStream, buffer);
				if (length < 0) {
					break;
				}
				write(outputStream, buffer, length);
			}
		} catch (IOException exception) {
		} finally {
			destroy();
		}
	}
	
	public void init() {
	}
	public void destroy() {
		try {
			inputStream.close();
		} catch (SocketException exception) {
		} catch (IOException exception) {
		}
		try {
			outputStream.close();
		} catch (SocketException exception) {
		} catch (IOException exception) {
		}
	}

	public int read(InputStream inputStream, byte[] buffer) throws IOException {
		return inputStream.read(buffer);
	}
	public void write(OutputStream outputStream, byte[] buffer, int length) throws IOException {
		outputStream.write(buffer, 0, length);
	}
}